<template>
  <div class="main">
    <div class="head_content">
      <span v-if="goodsType === 4">
        商品名称：
        <el-select v-model="listQuery.goodsId" placeholder="请选择商品" @change="handleChangeSelect">
          <el-option v-for="item in goods" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </span>
      <el-button type="primary" size="small" @click="addCommon" :disabled="upshelf===-1">新增评论</el-button>
    </div>

    <el-table :data="list" style="width: 100%" v-loading="listLoading" element-loading-text="给我一点时间">
      <el-table-column label="商品名称" prop="goodsName" width="180" align="center"></el-table-column>
      <el-table-column prop="nickname" label="会员名称" width="180" align="center"></el-table-column>
      <el-table-column prop="mobile" label="会员手机" width="180" align="center"></el-table-column>
      <el-table-column prop="score" label="评论分数" align="center"></el-table-column>
      <el-table-column label="排序" prop="sort" align="center" width="250">
        <template slot-scope="{ row, $index }">
          <div @click.stop="changeTableEidtble($index, 'editRemarkInput', true)">
            <div class="editSort" v-if="editable[$index]">
              <el-input-number v-model="row.sort" class="editRemarkInput" size="mini" :min="0"></el-input-number>
              <el-button type="primary" size="mini" plain @click="updataSort(row, $index)">保存</el-button>
              <el-button type="info" size="mini" plain @click.stop="changeTableEidtble($index, 'editRemarkInput', false)">取消</el-button>
            </div>
            <span v-else>
              {{ row.sort }}
              <i class="el-icon-edit"></i>
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="typeName" label="评论类型" align="center"></el-table-column>
      <el-table-column label="是否推荐" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.isBest === 1 ? "是" : "否" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="evaluateTime" label="评论时间" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="primary" plain @click="lookDetail(scope.row)">查看</el-button>
          <el-button type="danger" @click="_deleteCommont(scope.row)" plain>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page"
      :page-sizes="[10, 20, 50, 100]" :page-size="listQuery.pageSize" background layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
    <el-dialog :visible.sync="visibled" width="100%" v-if="type === 0">
      <div class="main">
        <section>
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
            <el-form-item prop="goodsId" label="评论商品">
              <el-select v-model="ruleForm.goodsId" placeholder="请选择商品">
                <el-option v-for="item in goods" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="评论时间" prop="evaluateTime">
              <el-date-picker type="datetime" :editable="false" placeholder="选择日期时间" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss"
                v-model="ruleForm.evaluateTime"></el-date-picker>
            </el-form-item>
            <el-form-item label="商品评分" prop="score">
              <el-input-number v-model="ruleForm.score" :step="1" :min="0" :max="5" :precision="0" placeholder="请输入商品评分"></el-input-number>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="ruleForm.sort" :min="0" placeholder="请输入商品评分"></el-input-number>
            </el-form-item>
            <el-form-item label="是否推荐" prop="isBest">
              <el-switch :active-value="1" :inactive-value="0" v-model="ruleForm.isBest"></el-switch>
            </el-form-item>
            <el-form-item label="评论内容" prop="content">
              <el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="ruleForm.content">
              </el-input>
            </el-form-item>
            <el-form-item label="图片评论">
              <el-upload :action="upladUrl" list-type="picture-card" :file-list="ruleForm.fileList" :limit="9" :before-upload="beforeUpload"
                :on-success="handleSuccess">
                <i class="el-icon-plus"></i>
                <div slot="tip" class="el-upload__tip">
                  1.上传图片支持JPG、GIF、JPEG、PNG格式。
                  2、最多允许上传9张照片。
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button type="info" @click="closeDialog">关闭</el-button>
              <el-button type="primary" @click="saveSubmit">保存</el-button>
            </el-form-item>
          </el-form>
        </section>
      </div>
    </el-dialog>
    <el-dialog v-else title="评论详情" :visible.sync="visibled">
      <div class="main">
        <section>
          <div class="container">
            <div class="item">
              <div class="item">
                <span>会员名称：</span>
                <span>{{ currentData.nickname }}</span>
              </div>
              <div class="item">
                <span>会员手机：</span>
                <span>{{ currentData.mobile }}</span>
              </div>
            </div>
            <div class="item">
              <div class="item">
                <span>评论时间：</span>
                <span>{{ currentData.evaluateTime }}</span>
              </div>
              <div class="item">
                <span>评论类型：</span>
                <span>{{ currentData.typeName }}</span>
              </div>
            </div>
            <div class="item">
              <div class="item">
                <span>商品评分：</span>
                <span>{{ currentData.score }}</span>
              </div>

              <div class="item">
                <span>排序：</span>
                <span>{{ currentData.sort }}</span>
              </div>
              <div class="item">
                <span>是否推荐：</span>
                <span>{{ currentData.isBest === 1 ? "是" : "否" }}</span>
              </div>
            </div>
            <div class="item">
              <span>评论内容：</span>
              <span v-html="currentData.content"></span>
            </div>
            <div class="item">
              <span>商品名称：</span>
              <span>{{ currentData.goodsName }}</span>
            </div>
            <div class="item">
              <p class="label">评论图片：</p>
              <div class="imgwrap">
                <img class="commontImg" v-for="(url, idx) in currentData.imageList" :key="idx" :src="url.imageUrl" />
              </div>
            </div>
          </div>
        </section>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateIsBest">
          {{
          currentData.isBest === 1 ? "不 推 荐" : "推 荐"
          }}
        </el-button>
        <el-button type="primary" @click="closeDialog">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCommontList,
  createCommont,
  getCommontDetail,
  setBestCommont,
  deleteCommont,
  setSortComont
} from '@/api/commont'
import { formatDate } from '@/utils/tools'
export default {
  name: 'commontTable',
  props: {
    goods: {
      type: Array,
      default() {
        return {}
      }
    },
    upshelf: {
      type: Number,
      default: 0
    },
    goodsType: {
      type: [String, Number],
      default: 0
    }
  },
  data() {
    return {
      currentData: {
        goodsName: this.goods[0].label
      },
      editable: [],
      type: 0,
      visibled: false,
      listLoading: false,
      total: 0,
      list: [],
      listQuery: {
        page: 0,
        pageSize: 10,
        goodsId: '',
        goodsType: ''
      },
      ruleForm: {
        fileList: [],
        imageList: [],
        content: '',
        isBest: false,
        goodsType: this.goodsType,
        score: '',
        sort: 0,
        evaluateTime: formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss'),
        goodsId: this.goods[0].value // 默认选择第一个
      },
      rules: {
        goodsId: [
          { required: true, message: '请选择评论商品', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入评论内容', trigger: 'blur' }
        ],
        isBest: [
          { required: true, message: '请选择是否推荐', trigger: 'change' }
        ],
        evaluateTime: [
          {
            required: true,
            message: '请选择日期',
            trigger: 'change'
          }
        ],
        sort: [
          {
            required: true,
            message: '请输入排序',
            trigger: 'blur'
          }
        ],
        score: [
          {
            required: true,
            message: '请输入评分',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.init()
    console.log('shij', this.goods)
  },
  methods: {
    init() {
      this.listQuery = {
        page: 0,
        pageSize: 10,
        goodsId: this.goods[0].value,
        goodsType: this.goodsType
      }
      this.getList()
    },
    async getList() {
      try {
        const { data } = await getCommontList(this.listQuery)
        console.log('@!@!', this.listQuery, this.goods)
        this.list = data.rows.map(it => {
          it.goodsName = this.currentData.goodsName
          return it
        })
        this.total = Number(data.total)
        this.listLoading = false
      } catch (error) {
        this.listLoading = false
        console.log(error)
      }
    },
    // 商品选择查询
    handleChangeSelect(val) {
      for (let it of this.goods) {
        if (it.value === val) {
          this.currentData.goodsName = it.label
          // this.listQuery.goodsName = it.label
          this.getList()
          return
        }
      }
    },
    changeTableEidtble(index, className, status) {
      if (!status) {
        this.getList()
      }
      // tableList为表格数据
      this.editable = new Array(this.list.length)
      this.editable[index] = status
      this.$set(this.editable, index, status)
      //让input自动获取焦点
      this.$nextTick(function() {
        const editInputList = document.getElementsByClassName(className)
        if (status) {
          editInputList[0].children[0].focus()
        }
      })
    },
    async lookDetail(val) {
      console.log('pl ', val)
      try {
        this.visibled = true
        this.type = 1
        const { data } = await getCommontDetail({ id: val.id })
        this.currentData = data
        this.currentData.goodsName = this.listQuery.goodsName
        console.log(data)
      } catch (error) {
        this.$message.error('获取详情失败')
        console.log(error)
      }
    },
    async updateIsBest() {
      try {
        const data = await setBestCommont({
          id: this.currentData.id,
          isBest: Number(!this.currentData.isBest)
        })
        if (data.message === 'SUCCESS') {
          this.$message.success('操作成功')
          this.closeDialog()
          this.getList()
        }
      } catch (error) {
        console.log(error)
        this.$message.error('操作失败')
      }
    },
    async _deleteCommont(val) {
      try {
        await this.$confirm('该操作会永久性删除此条评论，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const data = await deleteCommont({ id: val.id })
        if (data.message === 'SUCCESS') {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        }
      } catch (error) {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
    },
    async updataSort(val, index) {
      console.log('数据', val)
      try {
        const data = await setSortComont({ id: val.id, sort: val.sort })
        if (data.message === 'SUCCESS') {
          this.$message.success('操作成功')
          this.getList()
        }
      } catch (error) {
        console.log(error)
        this.$message.error('操作失败')
      }
      this.$set(this.editable, index, false)
    },
    // 新增评论
    addCommon() {
      this.visibled = true
      this.type = 0
    },
    saveSubmit() {
      this.$refs['ruleForm'].validate(async valid => {
        if (valid) {
          try {
            const data = await createCommont(this.ruleForm)
            if (data.message === 'SUCCESS') {
              this.$message.success('新增成功')
              this.closeDialog()
              this.getList()
            }
          } catch (error) {
            console.log(error)
          }
        } else {
          return false
        }
      })
    },
    handleSuccess(response, file, fileList) {
      if (fileList.length < 10) {
        this.ruleForm.imageList = []
        console.log('图片', fileList, fileList.length)
        fileList.forEach(it => {
          this.ruleForm.imageList.push({ imageUrl: it.response.filePath })
        })
      }
    },
    closeDialog() {
      this.visibled = false
      this.ruleForm.fileList = []
      this.ruleForm.imageList = []
      this.$refs.content && this.$refs.content.setContent('')
      this.$refs['ruleForm'] && this.$refs['ruleForm'].resetFields()
    },
    // 切换分页
    handleCurrentChange(page) {
      this.listQuery.page = page
      this.getList()
    },
    //切换每页条数
    handleSizeChange(value) {
      this.listQuery.pageSize = value
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.head_content {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.editSort {
  display: flex;
  align-items: center;
  cursor: pointer;
  justify-content: center;
}
.edit_icon {
  font-size: 16px;
}
/deep/ .el-dialog {
  max-width: 874px !important;
}
/deep/ .mce-container-body {
  width: 664px;
}
/deep/ .editor-container {
  width: 664px;
}
.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .item {
    display: flex;
    align-items: center;
    width: 100%;
    font-size: 16px;
    color: #333;
    margin-bottom: 20px;
    .label {
      white-space: nowrap;
    }
  }
}
.imgwrap {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .commontImg {
    margin: 0 20px 20px 0;
    width: 148px;
    height: 148px;
    border-radius: 4px;
  }
}
</style>
